package com.szw.trading.web.service.impl;

import java.math.BigDecimal;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.szw.trading.mybatis.entity.InvestmentSummary;
import com.szw.trading.mybatis.entity.Orders;
import com.szw.trading.mybatis.mapper.InvestmentSummaryMapper;
import com.szw.trading.mybatis.mapper.OrdersMapper;
import com.szw.trading.persistence.entity.CustomerTradingAccount;
import com.szw.trading.persistence.entity.Login;
import com.szw.trading.persistence.entity.Order;
import com.szw.trading.persistence.entity.RealTimeMarketdata;
import com.szw.trading.persistence.entity.Stock;
import com.szw.trading.persistence.repository.CustomerTradingAccountRepository;
import com.szw.trading.persistence.repository.LoginRepository;
import com.szw.trading.persistence.repository.StockRepository;
import com.szw.trading.web.bean.CancelOrderRequest;
import com.szw.trading.web.bean.CreateOrderRequest;
import com.szw.trading.web.bean.QueryOrderRequest;
import com.szw.trading.web.bean.RechargeAccountRequest;
import com.szw.trading.web.bean.Response;
import com.szw.trading.web.bean.SearchRequest;
import com.szw.trading.web.constants.Offsetted;
import com.szw.trading.web.constants.OrderQueueName;
import com.szw.trading.web.constants.OrderSide;
import com.szw.trading.web.constants.OrderStatus;
import com.szw.trading.web.service.BaseService;
import com.szw.trading.web.service.CustomerService;
import com.szw.util.HttpClientUtils;


@Service
public class CustomerServiceImpl extends BaseService implements CustomerService {

	@Autowired
	private LoginRepository loginRepository;
	@Autowired
	private CustomerTradingAccountRepository customerTradingAccountRepository;
	@Autowired
	private StockRepository stockRepository;
	@Autowired
	private OrdersMapper orderMapper;
	@Autowired
	private InvestmentSummaryMapper investmentSummaryMapper;
	@Value("${getMarketDataByCode.url}")
	private String getMarketDataByCodeUrl;

	@Value("${order.url}")
	private String orderUrl;

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
	public Response createOrder(Principal principal, CreateOrderRequest request) {
		request.setLoginId(principal.getName());
		// 调用order接口
		String returnStr = HttpClientUtils.doPost(orderUrl + "/createOrder", JSON.toJSONString(request));

		Response response = null;
		try {
			response = JSON.parseObject(returnStr, Response.class);
		} catch (Exception e) {
			log.error("[创建订单异常]", e);
		}
		return null != response ? response : Response.FAILUE("系统异常");
	}

	@Override
	public Response queryOrder(Principal principal, QueryOrderRequest request) {

		Login login = loginRepository.findByLoginId(Integer.valueOf(principal.getName()));
		CustomerTradingAccount cta = customerTradingAccountRepository.findByCustomerId(login.getCustomerId());

		PageHelper.startPage(request.getPageNo(), request.getPageSize());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tradingAccountId", cta.getTradingAccountId());
		map.put("stockCode", request.getKeyword());
		map.put("orderSide", OrderSide.BUY);
		map.put("orderType", request.getOrderType().equals("-1") ? null : request.getOrderType());
		map.put("status", request.getOrderStatus().equals("-1") ? null : request.getOrderStatus());
		PageInfo<Orders> pageInfo = new PageInfo<Orders>(orderMapper.selectByParams(map));

		return Response.SUCCESS(pageInfo);
	}

	public String genLimitOrderQueueName(Order order) {
		return OrderQueueName.LIMIT_ORDER_QUEUE.name() + ":" + order.getStockCode() + "-" + order.getOrderPrice();
	}

	@Override
	public Response cancelOrder(Principal principal, CancelOrderRequest request) {
		request.setLoginId(principal.getName());
		// 调用order接口
		String returnStr = HttpClientUtils.doPost(orderUrl + "/cancelOrder", JSON.toJSONString(request));

		Response response = null;
		try {
			response = JSON.parseObject(returnStr, Response.class);
		} catch (Exception e) {
			log.error("[创建订单异常]", e);
		}
		return null != response ? response : Response.FAILUE("系统异常");
	}

	@Override
	public Response queryInvestmentSummary(Principal principal, SearchRequest request) {
		Login login = loginRepository.findByLoginId(Integer.valueOf(principal.getName()));
		CustomerTradingAccount cta = customerTradingAccountRepository.findByCustomerId(login.getCustomerId());

		PageHelper.startPage(request.getPageNo(), request.getPageSize());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("tradingAccountId", cta.getTradingAccountId());
		PageInfo<InvestmentSummary> pageInfo = new PageInfo<InvestmentSummary>(investmentSummaryMapper.selectByParams(map));
		try {
			for (InvestmentSummary is : pageInfo.getList()) {
				BigDecimal floatingWinloss = BigDecimal.ZERO;
				String entity = HttpClientUtils.doGet(getMarketDataByCodeUrl + is.getStockCode());
				RealTimeMarketdata marketdata = JSON.parseObject(entity, RealTimeMarketdata.class);
				Stock stock = stockRepository.findByStockCode(marketdata.getStockcode());
				is.setStockName(stock.getStockName());
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("tradingAccountId", is.getTradingAccountId());
				params.put("stockCode", is.getStockCode());
				params.put("status", OrderStatus.SUCCESS);
				params.put("offsetted", Offsetted.NO_OFFSETTED);
				params.put("orderSide", OrderSide.BUY);
				List<Orders> orderList = orderMapper.selectByParams(params);
				for (Orders order : orderList) {
					floatingWinloss = floatingWinloss.add((marketdata.getNow().subtract(order.getOrderPrice())).multiply(order.getOrderHand()));
					is.setFloatingWinloss(floatingWinloss);
				}
			}
		} catch (Exception e) {
			log.error("【查询持仓列表报错】" + e);
		}

		return Response.SUCCESS(pageInfo);
	}

	@Override
	public Response queryAccount(Principal principal) {
		Login login = loginRepository.findByLoginId(Integer.valueOf(principal.getName()));
		CustomerTradingAccount cta = customerTradingAccountRepository.findByCustomerId(login.getCustomerId());

		return Response.SUCCESS(cta);
	}

	@Override
	public Response rechargeAccount(Principal principal, RechargeAccountRequest request) {

		Login login = loginRepository.findByLoginId(Integer.valueOf(principal.getName()));
		CustomerTradingAccount cta = customerTradingAccountRepository.findByCustomerId(login.getCustomerId());
		cta.setUsableAmount(cta.getUsableAmount().add(request.getAmount()));
		customerTradingAccountRepository.save(cta);

		return Response.SUCCESS(cta);
	}

}
